﻿using HomagChina.Basic.CCT.Db.CCHS_Db;
using HomagChina.Basic.CCT.Db.CCT_Db;
using HomagGroup.Base.UI.Windows;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Telerik.Windows.Data;
using LocalText = Proxy.Properties.Resources;

namespace Proxy
{
    public class ModifyInfoHandle
    {
        private CommonHandle Handle_Common;

        public ModifyInfoHandle()
        {
            Handle_Common = new CommonHandle();
        }

        public bool ModifyMachineConfig(T_MachineInfo t, int Id)
        {
            bool result = false;
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    var Info = Db.T_MachineInfo.FirstOrDefault(x => x.Id == Id);
                    Info.MachineNo = t.MachineNo;
                    Info.IP = t.IP;
                    Info.AvailableChannels = t.AvailableChannels;
                    Info.ModificationDate = DateTime.Now;
                    result = Db.SaveChanges() > 0;
                }
                return result;
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Modify.Error(ex.Message);
                return result;
            }
        }

        public bool ModifyLibraryConfig(T_CCHS_Position t, int Id)
        {
            bool result = false;
            try
            {
                using (Db_CCHS Db = new Db_CCHS())
                {
                    var Info = Db.T_CCHS_Position.FirstOrDefault(x => x.Id == Id);
                    Info.Positioncode = t.Positioncode;
                    Info.Baseheight = t.Baseheight;
                    Info.Xposition = t.Xposition;
                    Info.Yposition = t.Yposition;
                    Info.Rotate_Angle = t.Rotate_Angle;
                    Info.ModificationDate = DateTime.Now;
                    result = Db.SaveChanges() > 0;
                }
                return result;
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Modify.Error(ex.Message);
                return result;
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="TaskId"></param>
        public void ModifyTaskDetail(TaskInfoModel Task, int PickHeight, int PutHeight)
        {
            T_CCHS_Stock stockInfo = new T_CCHS_Stock();
            T_CCHS_StockDetail stockDetailInfo = new T_CCHS_StockDetail();
            try
            {
                using (Db_CCHS Db = new Db_CCHS())
                {
                    var TaskInfo = Db.T_CCHS_TaskDetail.FirstOrDefault(s => s.Id.Equals(Task.Id));
                    if (Task.BoardType.Equals(0))//垫板
                    {
                        var stock = Db.T_CCHS_Stock.Where(s => s.Positioncode.Equals(Task.TargetPosition)).FirstOrDefault();
                        var baseHeight = Db.T_CCHS_Position.FirstOrDefault(s => s.Positioncode.Equals(Task.TargetPosition)).Baseheight;
                        var stackHeight = Math.Ceiling((double)(stock.ActualQuantity * 18.5)) + baseHeight;
                        PutHeight = (int)stackHeight;
                    }
                    TaskInfo.SourcePositionH = PickHeight;
                    TaskInfo.TargetPositionH = PutHeight;
                    Db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Modify.Error(ex.Message);
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="TaskId"></param>
        public void ModifyTaskState(int TaskId, int State)
        {
            T_CCHS_Stock stockInfo = new T_CCHS_Stock();
            T_CCHS_StockDetail stockDetailInfo = new T_CCHS_StockDetail();
            var datetime = DateTime.Now;
            try
            {
                using (Db_CCHS Db = new Db_CCHS())
                {
                    var TaskInfo = Db.T_CCHS_TaskDetail.FirstOrDefault(s => s.Id.Equals(TaskId));
                    if (TaskInfo != null)
                    {
                        TaskInfo.TransferState = State;
                    }
                    Db.SaveChanges();
                    //根据任务状态来加减库存
                    switch (State)
                    {
                        case 20:
                            break;

                        case 30:

                            // 取料位置库存减1
                            UpdateStockQuantity(TaskInfo.SourcePosition, -1);

                            // 获取库存详细信息
                            UpdateStockInformation(TaskInfo.TargetPosition, TaskInfo.StackId, TaskInfo.Material, (int)TaskInfo.Tasktype, (int)TaskInfo.BoardType);

                            // 更新库存详细信息
                            UpdateStockDetail(TaskInfo.TargetPosition, TaskInfo.Material, TaskInfo.StackId, datetime);

                            // 更新任务状态
                            bool IsFlag = UpdateJobTaskState(TaskInfo.JobId);

                            if (IsFlag)
                            {
                                var jobInfo = Db.T_CCHS_JobList.FirstOrDefault(s => s.JobId == TaskInfo.JobId);

                                if (jobInfo == null)
                                {
                                    MessageBox.Show("JobInfo is null");
                                    return;
                                }
                                jobInfo.State = 30;
                                //删除JOB //后续改成作为历史记录
                                Db.T_CCHS_JobList.Remove(jobInfo);
                                var tasks = Db.T_CCHS_TaskDetail.Where(s => s.JobId == jobInfo.JobId).ToList();
                                Db.T_CCHS_TaskDetail.RemoveRange(tasks);

                                //预叠板任务
                                if (jobInfo.TargetType.Equals(3))
                                {
                                    var taskDetail = Db.T_CCHS_TaskDetail.Where(s => s.JobId == jobInfo.JobId).OrderByDescending(s => s.Layer).ToList();

                                    //生成一个新的Job
                                    T_CCHS_JobList t_CCHS_JobList = new T_CCHS_JobList()
                                    {
                                        JobId = "AO_" + datetime.ToString("yyyyMMddhhssfff"),
                                        StackId = jobInfo.Id.ToString(),
                                        Material = "Rainbow",
                                        JobType = 1,
                                        TargetType = 1,
                                        TargetPosition = "Outfeed01",
                                        TaskQuantity = jobInfo.TaskQuantity,
                                        Sort = jobInfo.Sort + 1,
                                        State = 10,
                                        CreationDate = datetime
                                    };
                                    Db.T_CCHS_JobList.Add(t_CCHS_JobList);

                                    int layer = 1;
                                    var First_dummyboard = "";

                                    var dummyboardInfo = Db.T_CCHS_Stock.OrderBy(s => s.ActualQuantity).FirstOrDefault(s => s.Material.Equals("垫板"));

                                    if (dummyboardInfo != null)
                                    {
                                        First_dummyboard = dummyboardInfo.Positioncode;
                                    }
                                    else
                                    {
                                        MessageBox.Show(LocalText.Empty_DummyBoard);
                                        return;
                                    }
                                    //添加一个垫板任务
                                    T_CCHS_TaskDetail t_CCHS_TaskDetail = new T_CCHS_TaskDetail()
                                    {
                                        JobId = t_CCHS_JobList.JobId,
                                        StackId = t_CCHS_JobList.StackId,
                                        StackType = 1,
                                        Material = "垫板",
                                        Boardcode = "DB_18",
                                        BoardType = 0,
                                        Layer = layer,
                                        SourcePosition = First_dummyboard,
                                        TargetPosition = "Outfeed01",
                                        Orientation = 0,
                                        Tasktype = 1,
                                        TransferState = 0,
                                        CreationDate = datetime,
                                    };
                                    Db.T_CCHS_TaskDetail.Add(t_CCHS_TaskDetail);
                                    layer++;
                                    //生成Tasks
                                    foreach (var item in taskDetail)
                                    {
                                        t_CCHS_TaskDetail = new T_CCHS_TaskDetail()
                                        {
                                            JobId = t_CCHS_JobList.JobId,
                                            StackId = t_CCHS_JobList.StackId,
                                            StackType = 1,
                                            BoardType = 1,
                                            Material = item.Material,
                                            Boardcode = item.Boardcode,
                                            SourcePosition = item.TargetPosition,
                                            TargetPosition = "Outfeed01",
                                            Layer = layer++,
                                            Orientation = 0,
                                            Tasktype = 1,
                                            TransferState = 0,
                                            CreationDate = datetime,
                                        };
                                        Db.T_CCHS_TaskDetail.Add(t_CCHS_TaskDetail);
                                    }
                                }

                                var outfeed = Db.T_CCHS_Stock.FirstOrDefault(s => s.Positioncode.Contains("Outfeed"));
                                if (TaskInfo.Tasktype.Equals(0) && outfeed != null)
                                {
                                    ClearStockItem(outfeed);
                                }
                                var clear = Db.T_CCHS_Stock.Where(s => s.ActualQuantity == 0).ToList();
                                foreach (var item in clear)
                                {
                                    ClearStockItem(item);
                                }
                                #region
                                ////库存源位置的信息要清掉
                                //var sourceStockInfo = Db.T_CCHS_Stock.FirstOrDefault(s => s.Positioncode == TaskInfo.SourcePosition);
                                ////如果是入库
                                //if (TaskInfo.Tasktype.Equals(0))
                                //{
                                //    sourceStockInfo.StackId = string.Empty;
                                //    sourceStockInfo.Material = string.Empty;
                                //    sourceStockInfo.ActualQuantity = 0;
                                //    sourceStockInfo.ActualHight = 0;
                                //    sourceStockInfo.VirtualQuantity = 0;
                                //    sourceStockInfo.VirtualHight = 0;
                                //    sourceStockInfo.CreationDate = null;
                                //    sourceStockInfo.ModificationDate = datetime;
                                //}
                                //else
                                //{
                                //    //如果是出库
                                //    //1.看哪几个位置出了板，各出多少张
                                //    var taskdetailInfo = Db.T_CCHS_TaskDetail.Where(s => s.JobId.Equals(TaskInfo.JobId)).ToList();

                                //    var sourcepositions = taskdetailInfo.GroupBy(s => s.SourcePosition);

                                //    foreach (var item in sourcepositions)
                                //    {
                                //        var o_stockInfo = Db.T_CCHS_Stock.FirstOrDefault(s=>s.Positioncode.Equals(item.Key.ToString()));
                                //        if (o_stockInfo.ActualQuantity.Equals(0))
                                //        {
                                //            sourceStockInfo.StackId = string.Empty;
                                //            sourceStockInfo.Material = string.Empty;
                                //            sourceStockInfo.ActualQuantity = 0;
                                //            sourceStockInfo.ActualHight = 0;
                                //            sourceStockInfo.VirtualQuantity = 0;
                                //            sourceStockInfo.VirtualHight = 0;
                                //            sourceStockInfo.CreationDate = null;
                                //            sourceStockInfo.ModificationDate = datetime;
                                //        }
                                //    }
                                //}
                                #endregion
                            }
                            break;

                        default:
                            break;
                    }
                    Db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Modify.Error(ex.Message);
            }
        }

        /// <summary>
        /// 清空数据
        /// </summary>
        /// <param name="stockItem"></param>
        private void ClearStockItem(T_CCHS_Stock stockItem)
        {
            stockItem.StackId = string.Empty;
            stockItem.Material = string.Empty;
            stockItem.ActualQuantity = 0;
            stockItem.ActualHight = 0;
            stockItem.VirtualQuantity = 0;
            stockItem.VirtualHight = 0;
            stockItem.CreationDate = null;
            stockItem.ModificationDate = DateTime.Now;
        }

        /// <summary>
        /// 取料位置库存增减
        /// </summary>
        /// <param name="positionCode"></param>
        /// <param name="quantityChange"></param>
        private void UpdateStockQuantity(string positionCode, int quantityChange)
        {
            using (Db_CCHS Db = new Db_CCHS())
            {
                var stockInfo = Db.T_CCHS_Stock.FirstOrDefault(s => s.Positioncode.Equals(positionCode));
                stockInfo.ActualQuantity += quantityChange;
                stockInfo.VirtualQuantity += quantityChange;

                if (quantityChange < 0)
                {
                    var stockDetailInfo = Db.T_CCHS_StockDetail
                        .Where(s => s.Positioncode.Equals(positionCode))
                        .OrderByDescending(s => s.Layer)
                        .FirstOrDefault();

                    if (stockDetailInfo != null)
                    {
                        Db.T_CCHS_StockDetail.Remove(stockDetailInfo);
                    }
                }
                Db.SaveChanges();
            }
        }

        /// <summary>
        /// 更新库存详细信息
        /// </summary>
        /// <param name="positionCode"></param>
        /// <param name="stackId"></param>
        /// <param name="material"></param>
        /// <param name="taskType"></param>
        /// <param name="boardType"></param>
        private void UpdateStockInformation(string positionCode, string stackId, string material, int taskType, int boardType)
        {
            using (Db_CCHS Db = new Db_CCHS())
            {
                var stockInfo = Db.T_CCHS_Stock.FirstOrDefault(s => s.Positioncode.Equals(positionCode));
                stockInfo.StackId = stackId;
                stockInfo.Material = (taskType == 0) ? material : (material.Contains("垫板") ? "" : material);

                if (!(taskType == 1 && boardType == 0))
                {
                    stockInfo.ActualQuantity += 1;
                    stockInfo.VirtualQuantity += 1;
                }
                Db.SaveChanges();
            }
        }

        /// <summary>
        /// 更新库存详细信息
        /// </summary>
        /// <param name="positionCode"></param>
        /// <param name="material"></param>
        /// <param name="stackId"></param>
        /// <param name="datetime"></param>
        private void UpdateStockDetail(string positionCode, string material, string stackId, DateTime datetime)
        {
            using (Db_CCHS Db = new Db_CCHS())
            {
                var stockDetailInfo = Db.T_CCHS_StockDetail
                .Where(s => s.Positioncode.Equals(positionCode))
                .OrderByDescending(s => s.Layer)
                .FirstOrDefault();

                int layer = (stockDetailInfo == null) ? 1 : (int)stockDetailInfo.Layer + 1;

                T_CCHS_StockDetail newlyStockDetailInfo = new T_CCHS_StockDetail()
                {
                    Positioncode = positionCode,
                    StackId = (material.Contains("垫板")) ? "垫板_" + datetime.ToString("yyyyMMddHHmmssfff") : stackId,
                    Material = material,
                    Layer = layer,
                    State = 0,
                    CreationDate = datetime,
                };
                Db.T_CCHS_StockDetail.Add(newlyStockDetailInfo);
                Db.SaveChanges();
            }
        }

        /// <summary>
        /// 更新任务状态
        /// </summary>
        /// <param name="jobId"></param>
        /// <returns></returns>
        private bool UpdateJobTaskState(string jobId)
        {
            using (Db_CCHS Db = new Db_CCHS())
            {
                var jobInfo = Db.T_CCHS_JobList.FirstOrDefault(s => s.JobId.Equals(jobId));
                List<T_CCHS_TaskDetail> taskInfoModels = Db.T_CCHS_TaskDetail.Where(s => s.JobId == jobInfo.JobId).ToList();
                return taskInfoModels.All(s => s.TransferState == 30);
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="Task"></param>
        /// <param name="Thinkness"></param>
        /// <returns></returns>
        public int ModifyPutHeight(TaskInfoModel Task, double Thinkness)
        {
            int PutHeight = 0;
            try
            {
                using (Db_CCHS Db = new Db_CCHS())
                {
                    var TaskInfo = Db.T_CCHS_TaskDetail.FirstOrDefault(s => s.Id.Equals(Task.Id));
                    var stock = Db.T_CCHS_Stock.Where(s => s.Positioncode.Equals(Task.TargetPosition)).FirstOrDefault();
                    var baseHeight = Db.T_CCHS_Position.FirstOrDefault(s => s.Positioncode.Equals(Task.TargetPosition)).Baseheight;
                    var stackHeight = Math.Ceiling((double)(stock.ActualQuantity * Thinkness)) + baseHeight;
                    PutHeight = (int)Math.Ceiling((double)stackHeight + Thinkness);
                    //if (Task.Tasktype.Equals(1))
                    //{
                    //    PutHeight = (int)Math.Ceiling((double)stackHeight + (Thinkness * 2));
                    //}
                }
                return PutHeight;
            }
            catch (Exception ex)
            {
                return PutHeight;
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="TaskId"></param>
        public void ModifyJobState(string JobId, int State)
        {
            try
            {
                using (Db_CCHS Db = new Db_CCHS())
                {
                    var JobInfo = Db.T_CCHS_JobList.FirstOrDefault(s => s.JobId.Equals(JobId));
                    if (JobInfo != null)
                    {
                        JobInfo.State = State;
                    }
                    Db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Modify.Error(ex.Message);
            }
        }

        /// <summary>
        /// 更新板件信息
        /// </summary>
        /// <param name="Location"></param>
        public bool ModifyBoardlibraryInfo(BoardlibraryModel model)
        {
            try
            {
                using (var Db = new Db_CCHS())
                {
                    T_CCHS_Boardlibrary t_CCHS_Boardlibrary = Db.T_CCHS_Boardlibrary.FirstOrDefault(s => s.Boardcode == model.Boardcode);
                    model.Id = t_CCHS_Boardlibrary.Id;
                    model.CreationDate = t_CCHS_Boardlibrary.CreationDate;
                    t_CCHS_Boardlibrary = Handle_Common.Mapper(t_CCHS_Boardlibrary, model);
                    t_CCHS_Boardlibrary.ModificationDate = DateTime.Now;
                    return Db.SaveChanges() > 0;
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Modify.Error(ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 重写sort
        /// </summary>
        /// <param name="Newlist"></param>
        /// <returns></returns>
        public bool ModifyJobListInfo(ObservableCollection<JobModel> Newlist)
        {
            try
            {
                using (var Db = new Db_CCHS())
                {
                    //重写排序
                    for (int i = 0; i < Newlist.Count; i++)
                    {
                        var item = Newlist[i];
                        var JobInfo = Db.T_CCHS_JobList.FirstOrDefault(s => s.Id == item.Id);
                        JobInfo.Sort = i;
                    }
                    return Db.SaveChanges() > 0;
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Modify.Error(ex.Message);
                return false;
            }
        }

        public bool ModifyJobListMoveTop(List<int> Ids)
        {
            bool result = false;

            List<T_CCHS_JobList> List_T = new List<T_CCHS_JobList>();

            try
            {
                using (var Db = new Db_CCHS())
                {
                    List_T.AddRange(Db.T_CCHS_JobList.OrderByDescending(b => b.State == 20).ThenBy(b => b.State).ToList());
                    for (int i = 0; i < Ids.Count; i++)
                    {
                        var item = List_T.FirstOrDefault(s => s.Id == Ids[i]);
                        if (item != null)
                        {
                            List_T.Remove(item);
                            List_T.Insert(List_T.FindLastIndex(s => s.State == 20) + 1, item);
                        }
                    }
                    //重写sort
                    for (int i = 0; i < List_T.Count; i++)
                    {
                        var item = List_T[i];
                        var JobInfo = Db.T_CCHS_JobList.FirstOrDefault(s => s.Id == item.Id);
                        if (JobInfo.State != 1)
                        {
                            JobInfo.Sort = i;
                        }
                    }

                    result = Db.SaveChanges() > 0;
                }
                return result;
            }
            catch (Exception ex)
            {
                return result;
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="StockModel"></param>
        /// <param name="SelectedValue"></param>
        /// <param name="ActualQuantity"></param>
        public void ModifyStockInfo(T_CCHS_Stock StockModel, string SelectedValue, int ActualQuantity)
        {
            try
            {
                using (Db_CCHS Db = new Db_CCHS())
                {
                    int CurrentQuantity = Db.T_CCHS_StockDetail.Where(s => s.Positioncode.Equals(StockModel.Positioncode) && s.Material.Equals(StockModel.Material)).Count();
                    Db.T_CCHS_StockDetail.RemoveRange(Db.T_CCHS_StockDetail.Where(s => s.Positioncode == StockModel.Positioncode));
                    for (int i = 0; i < ActualQuantity; i++)
                    {
                        T_CCHS_StockDetail NewlyStockDetailInfo = new T_CCHS_StockDetail()
                        {
                            Positioncode = StockModel.Positioncode,
                            StackId = StockModel.StackId,
                            Material = SelectedValue,
                            Layer = i + 1,
                            State = 0,
                            CreationDate = DateTime.Now,
                        };
                        Db.T_CCHS_StockDetail.Add(NewlyStockDetailInfo);
                    }
                    Db.SaveChanges();
                    T_CCHS_Stock stockInfo = Db.T_CCHS_Stock.FirstOrDefault(s => s.Positioncode.Equals(StockModel.Positioncode));
                    stockInfo.ActualQuantity = ActualQuantity;
                    stockInfo.Material = SelectedValue;
                    stockInfo.ModificationDate = DateTime.Now;
                    Db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Modify.Error(ex.Message);
            }
        }

        public void ModifyGantryPosition(int x, int y, int r, bool hasboard)
        {
            try
            {
                using (Db_CCHS Db = new Db_CCHS())
                {
                    var info = Db.T_CCHS_GantryPosition.FirstOrDefault();
                    info.X = float.Parse(x.ToString());
                    info.Y = float.Parse(y.ToString());
                    info.R = float.Parse(r.ToString());
                    info.HasBoard = hasboard == true ? 1 : 0;
                    Db.SaveChanges();
                }
            }
            catch (Exception ex)
            {

            }
        }
    }
}